#include "config.h"

#include "ms2lstat.h"

char	*confpath = "ms2lstat.conf";

static ECMBOOL
setup_sr_conf(sr_t *sr_conf)
{
	sr_t	*sr_arrival_duration;
	sr_t	*sr_start_hourzone;
	sr_t	*sr_end_hourzone;
	sr_t	*sr_mod;
	sr_t	*sr_suppress_display_error;
	sr_t	*sr_no_suffix_logging;
	sr_t	*sr_session_gap;
	sr_t	*sr_exclude_day;

	if ((sr_arrival_duration = sr_getc(sr_conf, "arrival_duration"))) {
		arrival_duration = sr_get_int(sr_arrival_duration);
	}

	if ((sr_start_hourzone = sr_getc(sr_conf, "start_hourzone"))) {
		start_hourzone = sr_get_int(sr_start_hourzone);
	}

	if ((sr_end_hourzone = sr_getc(sr_conf, "end_hourzone"))) {
		end_hourzone = sr_get_int(sr_end_hourzone);
	}

	if ((sr_mod = sr_getc(sr_conf, "modpath"))) {
		lparser_modpath = ecm_strdup(sr_get_str(sr_mod));
	}

	if ((sr_session_gap = sr_getc(sr_conf, "session_gap"))) {
		session_gap = sr_get_int(sr_session_gap);
	}

	if ((sr_suppress_display_error = sr_getc(sr_conf, "suppress_display_error"))) {
		suppress_display_error = sr_get_bool(sr_suppress_display_error);
	}

	if ((sr_no_suffix_logging = sr_getc(sr_conf, "no_suffix_logging"))) {
		no_suffix_logging = sr_get_bool(sr_no_suffix_logging);
	}

	if ((sr_exclude_day = sr_getc(sr_conf, "exclude_day"))) {
		exclude_day = sr_get_int(sr_exclude_day);
	}

	return ECM_TRUE;
}

static sr_t *
load_sr_conf(const char *confpath)
{
	sr_t	*sr;
	char	*buf;
	ecm_size_t	size;
	int	fd;

	fd = ecm_open(confpath, ECM_O_RDONLY);
	if (fd < 0)
		return NULL;
	if (!ecm_filesize(fd, &size)) {
		ecm_close(fd);
		return NULL;
	}
	buf = (char *)ecm_malloc(size + 1);
	if (buf == NULL) {
		ecm_close(fd);
		return NULL;
	}
	buf[size] = '\0';

	if (!ecm_read(fd, buf, &size)) {
		ecm_close(fd);
		return NULL;
	}
	sr = sr_asr_scan(buf);
	ecm_close(fd);

	return sr;
}

ECMBOOL
init_lstatconf(void)
{
	sr_t	*sr_conf;
	ECMBOOL	res;

	if (ecm_empty_str(confpath) || !ecm_access(confpath, ECM_R_OK))
		return ECM_TRUE;

	sr_conf = load_sr_conf(confpath);

	if (sr_conf == NULL) {
		ERR("%s: cannot load configuration", confpath);
		return ECM_FALSE;
	}

	res = setup_sr_conf(sr_conf);

	sr_free(sr_conf);

	return res;
}
